<template>
  <div class="min-h-screen">
    <!-- Hero Section -->
    <section class="bg-gradient-to-br from-primary-50 to-blue-50 py-20">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center">
          <h1 class="text-4xl md:text-6xl font-bold text-gray-900 mb-6">
            <span class="animate-bounce-in">欢迎来到</span>
            <span class="text-primary-600 animate-gradient-text">我的博客</span>
          </h1>
          <p class="text-xl text-gray-600 mb-8 max-w-3xl mx-auto animate-fade-in-up">
            <span class="animate-typing">在这里分享技术见解，记录生活点滴，用文字记录成长，用代码改变世界</span>
          </p>
          <div class="flex flex-col sm:flex-row gap-4 justify-center">
            <router-link to="/blog" class="btn-primary text-lg px-8 py-3 animate-bounce-hover">
              阅读博客
            </router-link>
            <router-link to="/about" class="btn-secondary text-lg px-8 py-3 animate-bounce-hover">
              了解更多
            </router-link>
          </div>
        </div>
      </div>
    </section>

    <!-- Auto Snake Game Section -->
    <section class="py-20 bg-gradient-to-br from-green-50 via-emerald-50 to-teal-50 relative overflow-hidden">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        <!-- Game Container -->
        <div class="flex justify-center">
          <!-- Game Board -->
          <div class="bg-white rounded-2xl shadow-2xl p-6 border-4 border-green-200">
            <div class="text-center mb-4">
              <div class="text-sm text-gray-500 mb-2">
                速度: {{ gameSpeed }}ms | 长度: {{ snake.length }}
              </div>
            </div>
            
            <!-- Canvas for Snake Game -->
            <canvas 
              ref="gameCanvas"
              :width="canvasSize"
              :height="canvasSize"
              class="border-2 border-gray-300 rounded-lg bg-gray-900"
              style="image-rendering: pixelated;"
            ></canvas>
            
            <!-- Game Controls -->
            <div class="flex justify-center gap-4 mt-4">
              <button 
                @click="toggleGame"
                :class="isPlaying ? 'bg-red-500 hover:bg-red-600' : 'bg-green-500 hover:bg-green-600'"
                class="px-6 py-2 text-white rounded-lg font-semibold transition-colors duration-200"
              >
                {{ isPlaying ? '暂停' : '开始' }}
              </button>
              <button 
                @click="resetGame"
                class="px-6 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-semibold transition-colors duration-200"
              >
                重置
              </button>
            </div>
          </div>
        </div>

        <!-- Game Status -->
        <div class="text-center mt-8">
          <div v-if="gameOver" class="bg-yellow-100 border border-yellow-300 text-yellow-700 px-6 py-3 rounded-lg inline-block">
            <span class="font-bold">游戏结束!</span> 1秒后自动重新开始...
          </div>
          <div v-else class="bg-green-100 border border-green-300 text-green-700 px-6 py-3 rounded-lg inline-block">
            <span class="font-bold">AI自动游戏运行中...</span>
          </div>
        </div>
      </div>
    </section>

    <!-- Stats Section -->
    <section class="py-20 bg-gray-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8 text-center">
          <div class="bg-white p-8 rounded-xl shadow-sm animate-slide-in-left">
            <div class="text-4xl font-bold text-primary-600 mb-2 animate-count-up">{{ stats.totalPosts }}</div>
            <div class="text-gray-600 animate-fade-in">发表文章</div>
          </div>
          <div class="bg-white p-8 rounded-xl shadow-sm animate-slide-in-right">
            <div class="text-4xl font-bold text-primary-600 mb-2 animate-count-up">{{ stats.totalViews }}</div>
            <div class="text-gray-600 animate-fade-in">总阅读量</div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { getArticles } from '../services/articleService'
import { getTotalViews, loadViewsData, incrementViews } from '../services/viewsService'

const allArticles = ref([])
const loading = ref(true)
const totalViews = ref(0) // 响应式总阅读量

// 获取最新文章（前3篇）
const latestPosts = computed(() => {
  return allArticles.value.slice(0, 3)
})

// 更新总阅读量
const updateTotalViews = () => {
  totalViews.value = getTotalViews()
  console.log('总阅读量已更新:', totalViews.value)
}

// 监听阅读量更新事件
const handleViewsUpdate = (event) => {
  console.log('收到阅读量更新事件:', event.detail)
  updateTotalViews()
}


// 统计数据
const stats = computed(() => {
  return {
    totalPosts: allArticles.value.length,
    totalViews: totalViews.value
  }
})

// 加载文章数据
const loadArticles = async () => {
  try {
    loading.value = true
    allArticles.value = await getArticles()
  } catch (error) {
    console.error('加载文章失败:', error)
  } finally {
    loading.value = false
  }
}

// 贪吃蛇游戏相关状态
const gameCanvas = ref(null)
const canvasSize = 400
const gridSize = 20
const gridCount = canvasSize / gridSize

// 游戏状态
const isPlaying = ref(false)
const gameOver = ref(false)
const score = ref(0)
const highScore = ref(0)
const gameSpeed = ref(150)
const gameCount = ref(0)
const startTime = ref(0)
const survivalTime = ref(0)

// 蛇的状态
const snake = ref([{ x: 10, y: 10 }])
const direction = ref({ x: 1, y: 0 })
const food = ref({ x: 15, y: 15 })

// 游戏循环
let gameLoop = null

// 计算属性（保留用于可能的未来功能）
const averageScore = computed(() => {
  return gameCount.value > 0 ? Math.round(score.value / gameCount.value) : 0
})

const efficiency = computed(() => {
  return survivalTime.value > 0 ? Math.round((score.value / survivalTime.value) * 100) / 100 : 0
})

// 生成随机食物位置
const generateFood = () => {
  let newFood
  do {
    newFood = {
      x: Math.floor(Math.random() * gridCount),
      y: Math.floor(Math.random() * gridCount)
    }
  } while (snake.value.some(segment => segment.x === newFood.x && segment.y === newFood.y))
  
  food.value = newFood
}

// AI寻路算法 - 简单的A*寻路
const findPath = () => {
  const head = snake.value[0]
  const target = food.value
  
  // 简单的贪心算法：优先朝食物方向移动
  const dx = target.x - head.x
  const dy = target.y - head.y
  
  let newDirection = { x: 0, y: 0 }
  
  // 选择移动方向
  if (Math.abs(dx) > Math.abs(dy)) {
    newDirection.x = dx > 0 ? 1 : -1
  } else {
    newDirection.y = dy > 0 ? 1 : -1
  }
  
  // 检查是否会撞墙或撞到自己
  const newHead = {
    x: head.x + newDirection.x,
    y: head.y + newDirection.y
  }
  
  // 边界检查
  if (newHead.x < 0 || newHead.x >= gridCount || newHead.y < 0 || newHead.y >= gridCount) {
    // 如果会撞墙，尝试其他方向
    if (newDirection.x !== 0) {
      newDirection.x = 0
      newDirection.y = dy > 0 ? 1 : -1
    } else {
      newDirection.y = 0
      newDirection.x = dx > 0 ? 1 : -1
    }
  }
  
  // 检查是否会撞到自己
  const testHead = {
    x: head.x + newDirection.x,
    y: head.y + newDirection.y
  }
  
  if (snake.value.some(segment => segment.x === testHead.x && segment.y === testHead.y)) {
    // 如果会撞到自己，尝试转向
    if (newDirection.x !== 0) {
      newDirection.x = 0
      newDirection.y = Math.random() > 0.5 ? 1 : -1
    } else {
      newDirection.y = 0
      newDirection.x = Math.random() > 0.5 ? 1 : -1
    }
  }
  
  direction.value = newDirection
}

// 移动蛇
const moveSnake = () => {
  if (!isPlaying.value || gameOver.value) return
  
  findPath() // AI决定移动方向
  
  const head = { ...snake.value[0] }
  head.x += direction.value.x
  head.y += direction.value.y
  
  // 检查边界碰撞
  if (head.x < 0 || head.x >= gridCount || head.y < 0 || head.y >= gridCount) {
    endGame()
    return
  }
  
  // 检查自身碰撞
  if (snake.value.some(segment => segment.x === head.x && segment.y === head.y)) {
    endGame()
    return
  }
  
  snake.value.unshift(head)
  
  // 检查是否吃到食物
  if (head.x === food.value.x && head.y === food.value.y) {
    score.value++
    if (score.value > highScore.value) {
      highScore.value = score.value
    }
    generateFood()
  } else {
    snake.value.pop()
  }
}

// 绘制游戏
const drawGame = () => {
  if (!gameCanvas.value) return
  
  const ctx = gameCanvas.value.getContext('2d')
  ctx.fillStyle = '#1f2937' // 深灰色背景
  ctx.fillRect(0, 0, canvasSize, canvasSize)
  
  // 绘制网格
  ctx.strokeStyle = '#374151'
  ctx.lineWidth = 1
  for (let i = 0; i <= gridCount; i++) {
    ctx.beginPath()
    ctx.moveTo(i * gridSize, 0)
    ctx.lineTo(i * gridSize, canvasSize)
    ctx.moveTo(0, i * gridSize)
    ctx.lineTo(canvasSize, i * gridSize)
    ctx.stroke()
  }
  
  // 绘制蛇
  snake.value.forEach((segment, index) => {
    if (index === 0) {
      // 蛇头 - 黄色
      ctx.fillStyle = '#fbbf24'
    } else {
      // 蛇身 - 绿色
      ctx.fillStyle = '#10b981'
    }
    ctx.fillRect(
      segment.x * gridSize + 1,
      segment.y * gridSize + 1,
      gridSize - 2,
      gridSize - 2
    )
  })
  
  // 绘制食物 - 红色
  ctx.fillStyle = '#ef4444'
  ctx.fillRect(
    food.value.x * gridSize + 1,
    food.value.y * gridSize + 1,
    gridSize - 2,
    gridSize - 2
  )
}

// 游戏主循环
const gameStep = () => {
  if (!isPlaying.value || gameOver.value) return
  
  moveSnake()
  drawGame()
  
  if (isPlaying.value && !gameOver.value) {
    gameLoop = setTimeout(gameStep, gameSpeed.value)
  }
}

// 开始/暂停游戏
const toggleGame = () => {
  if (gameOver.value) return
  
  isPlaying.value = !isPlaying.value
  
  if (isPlaying.value) {
    startTime.value = Date.now()
    gameStep()
  } else {
    if (gameLoop) {
      clearTimeout(gameLoop)
      gameLoop = null
    }
  }
}

// 自动开始游戏
const autoStartGame = () => {
  isPlaying.value = true
  startTime.value = Date.now()
  gameStep()
}

// 重置游戏
const resetGame = () => {
  isPlaying.value = false
  gameOver.value = false
  score.value = 0
  snake.value = [{ x: 10, y: 10 }]
  direction.value = { x: 1, y: 0 }
  generateFood()
  
  if (gameLoop) {
    clearTimeout(gameLoop)
    gameLoop = null
  }
  
  drawGame()
}

// 结束游戏
const endGame = () => {
  isPlaying.value = false
  gameOver.value = true
  gameCount.value++
  
  if (startTime.value > 0) {
    survivalTime.value = Math.round((Date.now() - startTime.value) / 1000)
  }
  
  if (gameLoop) {
    clearTimeout(gameLoop)
    gameLoop = null
  }
  
  // 自动重新开始游戏
  setTimeout(() => {
    resetGame()
    autoStartGame()
  }, 1000) // 1秒后自动重新开始
}

// 组件挂载时初始化
onMounted(async () => {
  loadArticles()
  
  // 初始化阅读量数据（异步加载）
  await loadViewsData()
  updateTotalViews()
  
  // 初始化游戏并自动开始
  setTimeout(() => {
    generateFood()
    drawGame()
    autoStartGame() // 自动开始游戏
  }, 100)
  
  // 监听阅读量更新事件
  window.addEventListener('viewsUpdated', handleViewsUpdate)
  
  // 定期重新加载views.txt文件（每3秒检查一次文件变化）
  const viewsInterval = setInterval(async () => {
    await loadViewsData() // 重新从文件加载数据
    updateTotalViews() // 更新显示
  }, 3000)
  
  // 组件卸载时清理定时器和事件监听
  onUnmounted(() => {
    clearInterval(viewsInterval)
    window.removeEventListener('viewsUpdated', handleViewsUpdate)
  })
})

</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 跳动进入动画 */
@keyframes bounceIn {
  0% {
    opacity: 0;
    transform: scale(0.3) translateY(-50px);
  }
  50% {
    opacity: 1;
    transform: scale(1.05) translateY(0);
  }
  70% {
    transform: scale(0.9);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.animate-bounce-in {
  animation: bounceIn 1s ease-out;
}

/* 渐变动画文字 */
@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.animate-gradient-text {
  background: linear-gradient(-45deg, #3b82f6, #8b5cf6, #06b6d4, #10b981);
  background-size: 400% 400%;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: gradientShift 3s ease infinite;
}

/* 淡入上升动画 */
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(30px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in-up {
  animation: fadeInUp 1s ease-out 0.5s both;
}

/* 打字机效果 */
@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

@keyframes blink {
  50% {
    border-color: transparent;
  }
}

.animate-typing {
  overflow: hidden;
  border-right: 2px solid #3b82f6;
  white-space: nowrap;
  animation: typing 3s steps(40, end), blink 0.75s step-end infinite;
  animation-delay: 1s;
  animation-fill-mode: both;
}

/* 悬停跳动效果 */
@keyframes bounceHover {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

.animate-bounce-hover {
  transition: all 0.3s ease;
}

.animate-bounce-hover:hover {
  animation: bounceHover 0.6s ease-in-out;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 滑入动画 */
@keyframes slideInLeft {
  0% {
    opacity: 0;
    transform: translateX(-50px);
  }
  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  0% {
    opacity: 0;
    transform: translateX(50px);
  }
  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

.animate-slide-in-left {
  animation: slideInLeft 0.8s ease-out 0.2s both;
}

.animate-slide-in-right {
  animation: slideInRight 0.8s ease-out 0.4s both;
}

/* 计数动画 */
@keyframes countUp {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.animate-count-up {
  animation: countUp 1s ease-out 0.6s both;
}

/* 淡入动画 */
@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.animate-fade-in {
  animation: fadeIn 1s ease-out 0.8s both;
}

/* Game canvas styling */
canvas {
  display: block;
  margin: 0 auto;
  border-radius: 8px;
}

/* Game button animations */
button {
  transition: all 0.2s ease-in-out;
}

button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

button:active {
  transform: translateY(0);
}

/* Game status animations */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

.bg-green-100 {
  animation: pulse 2s ease-in-out infinite;
}

/* Game info panel hover effects */
.bg-white\/90:hover {
  transform: translateY(-2px);
  transition: transform 0.3s ease;
}
</style>
